<?php

/**
 * User models
 *
 * User models in console
 *
 * PHP Version: 1.2.3
 *
 * @author Johari <joharijumali@gmail.com>
 */

/**
 * Class User
 *
 * Class User in console models
 *
 * @author Johari <joharijumali@gmail.com>
 */

class Console_User extends Eloquent
{

    public static $timestamps = true;
    public static $table = 'sys_user';
    public static $key = 'su_id';

    public static $rules = array(
                                'su_username' => 'required',
                                'su_password' => 'required',
                                'sur_id' => 'required|not_in:0'
                            );

	/**
     * Function validate that pass parameter
     *
     * @param varchar $data the varchar to quote
	 *
	 * @return parameter.
     */
    public static function validate($data)
	{
        return Validator::make($data, Static::$rules);
    }
	
	/**
     * Function profile
	 *
	 * @return profile.
     */
    public function profile()
    {
        return $this->has_one('Console_Profile', 'su_id');
    }
	
	/**
     * Function roles
	 *
	 * @return roles.
     */
    public function roles()
    {
        return $this->has_one('Console_Role', 'sur_id');
    }
	
	/**
     * Function confirmUser that pass parameter
     *
     * @param varchar $input the varchar to quote
     * @param int     $id    the integer to quote
	 *
	 * @return parameter.
     */
    public static function confirmUser($input, $id = 0)
	{
        if ($id != 0) {
            $user = Console_User::find($id);
            $user->su_password = Hash::make($input['su_password']);
            $user->su_status = 1;
            $user->save();
            return true;
        } else {
            return false;
        }
    }

	/**
     * Function registerUser that pass parameter
     *
     * @param varchar $input the varchar to quote
	 *
	 * @return parameter.
     */
    public static function registerUser($input)
	{
        $User = new Console_User;
        
        $id = $User->insert_get_id(array(
			'su_username' => $input['su_username'], 
            'su_password' => Hash::make($input['su_password']), 
            'su_validationkey' => $input['key'], 
            'created_at' => date("Y-m-d H:i:s"), 
            'updated_at' => date("Y-m-d H:i:s"), 
            'su_status' => 3, //1=active, 3=pending confirmation, 2=unactive, 4=new
            'sur_id' => $input['sur_id']
		));

        unset($input['su_username']);
        unset($input['su_password']);
        unset($input['sur_id']);
        unset($input['key']);

        if ($id) {

			// $extension = File::extension($input['imgpath']['name']);
			// $directory = path('public').'avatar/'.sha1($id);
			// $filename = sha1($id.time()).".{$extension}";

			// if($input['imgpath']['size'] != null){

			//     $upload_success = Input::upload('photo', $directory, $filename);

			//     if( $upload_success ) {
			//         $input['imgpath'] = 'avatar/'.sha1($id).'/'.$filename;
			//     }else{
			//         $input['imgpath'] = '';
			//     }
			// }else{
			//     $input['imgpath'] = '';
			// }

            $profile = new Console_Profile(array(
                'sup_nama' => $input['sup_nama'],
                'sup_no_ic' => $input['sup_no_ic'],
                'sup_emel' => $input['sup_emel'],
                'sup_tel' => $input['sup_tel'],
                'sup_no_pekerja' => $input['sup_no_pekerja'],
                'wjkp_no_auto' => $input['wjkp_no_auto'],
                'wpj_no_auto' => $input['wpj_no_auto'],
                'wpb_no_auto' => $input['wpb_no_auto'],
                'wpu_no_auto' => $input['wpu_no_auto'],
                'sup_is_supervisor' => isset($input['sup_is_supervisor'])?1:0,
                'sup_penyelia_satu' => $input['sup_penyelia_satu'],
                'sup_penyelia_dua' => $input['sup_penyelia_dua'],
                'wp_tarikh_mula' => date('Y-m-d', strtotime($input['wp_tarikh_mula'])),
                'wp_tarikh_tamat' => (isset($input['wp_tarikh_tamat']))?date('d-m-Y', strtotime($input['wp_tarikh_tamat'])):'0000-00-00',
                'wp_kemaskini_oleh' =>  Auth::user()->su_id, 
                'created_at' =>  date("Y-m-d H:i:s"), 
                'updated_at' =>  date("Y-m-d H:i:s"),
                'sup_tidak_kelihatan' => isset($input['sup_tidak_kelihatan'])?1:0,
                'sup_id_pengguna' => $input['sup_id_pengguna']
            ));

            $user = Console_User::find($id);
            $user->profile()->insert($profile);

            Log::write('User', 'User '.$input['sup_no_ic'].' registered By <code>'.Auth::user()->su_username.'</code>');
			Trail::log(
				'Pengguna', 
				Auth::user()->su_id, 
				'Pengguna '.$input['sup_no_ic'].' didaftarkan Oleh <code>'.Auth::user()->su_username.'</code>'
			);

            return $profile->exists; 
        } else {
            Log::write('User', 'User '.$input['sup_no_ic'].' failed registered');
			Trail::log('Pengguna', Auth::user()->su_id, 'Pengguna '.$input['sup_no_ic'].' gagal didaftarkan');
			
            return false;			
        }
    }
	
	/**
     * Function listUser
	 *
	 * @return listUser.
     */
    public static function listUser()
	{	
        $allUser = Console_User::join('sys_user_profile', 'sys_user.su_id', '=', 'sys_user_profile.su_id')
			->paginate(Config::get('system.pagination'));
		
        $datagrid = new Datagrid;
        $datagrid->setFields(array('profile/sup_id_pengguna' => Str::upper(Lang::line('admin.tagid')->get())));
        $datagrid->setFields(array('profile/sup_nama' => Str::upper(Lang::line('admin.fullname')->get())));
        $datagrid->setFields(array('profile/sup_emel' => Str::upper(Lang::line('admin.activeemel')->get())));
        $datagrid->setFields(array('profile/sup_no_ic' => Str::upper(Lang::line('admin.idno')->get())));
        //$datagrid->setFields(array('sur_id' => Str::upper(Lang::line('Jawatan ??')->get())));
        //$datagrid->setFields(array('profile/sup_is_supervisor' => Str::upper(Lang::line('Penyelia ??')->get())));
        $datagrid->setFields(array('su_status' => Str::upper('Status')));
        $datagrid->setAction(Lang::line('global.edit')->get(), 'viewUser', true, array('su_id', 'su_status','sur_id'));
        $datagrid->setAction(Lang::line('global.delete')->get(), 'deleteAccount', true, array('su_id', 'sup_id_pengguna'));
        $datagrid->setAction(Lang::line('global.reset')->get(), 'resetAccount', true, array('su_id', 'sup_id_pengguna'));
        $datagrid->setTable('users', 'table table-bordered table-hover table-striped table-condensed');
        $datagrid->build($allUser, 'su_id');

        return $datagrid->render();
    }    

	/**
     * Function userSearchList that pass parameter
     *
     * @param varchar $input the varchar to quote
	 *
	 * @return parameter.
     */
    public static function userSearchList($input)
	{
        $operator = (stripos($input['searchval'], '*'))? 'LIKE':'=';
        $val = str_replace("*", "", $input['searchval']);
        $refval = (stripos($input['searchval'], '*'))? '%'.$val.'%':$val;

        $allUser = Console_User::left_join('sys_user_profile', 'sys_user.su_id', '=', 'sys_user_profile.su_id')
                    ->where('sys_user_profile.sup_no_ic', $operator, $refval)
                    ->or_where('sys_user_profile.sup_nama', $operator, $refval)
                    ->or_where('sys_user_profile.sup_id_pengguna', $operator, $refval)
                    ->paginate(Config::get('system.pagination'));

        $allUser->appends(array('searchval' => $input['searchval']))->links();

        $datagrid = new Datagrid;
        $datagrid->setFields(array('profile/sup_id_pengguna' => Str::upper(Lang::line('admin.tagid')->get())));
        $datagrid->setFields(array('profile/sup_nama' => Str::upper(Lang::line('admin.fullname')->get())));
        $datagrid->setFields(array('profile/sup_emel' => Str::upper(Lang::line('admin.activeemel')->get())));
        $datagrid->setFields(array('profile/sup_no_ic' => Str::upper(Lang::line('admin.idno')->get())));
        $datagrid->setFields(array('su_status' => Str::upper('Status')));
        $datagrid->setAction(Lang::line('global.edit')->get(), 'viewUser', true, array('su_id', 'su_status','sur_id'));
        $datagrid->setAction(Lang::line('global.delete')->get(), 'deleteAccount', true, array('su_id', 'sup_id_pengguna'));
        $datagrid->setAction(Lang::line('global.reset')->get(), 'resetAccount', true, array('su_id', 'sup_id_pengguna'));
        $datagrid->setTable('users', 'table table-bordered table-hover table-striped table-condensed');
        $datagrid->build($allUser, 'su_id');

        return $datagrid->render();
    }

	/**
     * Function userinfo that pass parameter
     *
     * @param integer $id the integer to quote
	 *
	 * @return parameter.
     */
    public static function userinfo($id)
	{
        $userInfo = Console_User::find($id);
        $profile = $userInfo->profile;
        $role = $userInfo->roles;

        $data['sup_no_pekerja'] = $profile->sup_no_pekerja;
        $data['sup_id_pengguna'] = $profile->sup_id_pengguna;
        $data['sup_tel'] = $profile->sup_tel;
        $data['wp_tarikh_mula'] = ($profile->sup_tarikh_mula != '0000-00-00')?date('d-m-Y', strtotime($profile->sup_tarikh_mula)):null;
        $data['wp_tarikh_tamat'] = ($profile->sup_tarikh_tamat != '0000-00-00')?date('d-m-Y', strtotime($profile->sup_tarikh_tamat)):null;
        $data['wjkp_no_auto'] = $profile->sukp_no_auto;
        $data['wpj_no_auto'] = $profile->suj_no_auto;
        $data['wpb_no_auto'] = $profile->sub_no_auto;
        $data['wpu_no_auto'] = $profile->suu_no_auto;
        $data['sup_penyelia_satu'] = $profile->sup_penyelia_satu;
        $data['sup_penyelia_dua'] = $profile->sup_penyelia_dua;
        $data['sup_tidak_kelihatan'] = $profile->sup_tidak_kelihatan;
        $data['su_username'] = $userInfo->su_username;
        $data['sup_nama'] = $profile->sup_nama;
        $data['sup_no_ic'] = $profile->sup_no_ic;
        $data['sup_emel'] = $profile->sup_emel;
        $data['sup_is_supervisor'] = $profile->sup_is_supervisor;
        $data['sur_id'] = $userInfo->sur_id;
        $data['su_status'] = $userInfo->su_status;
        $data['su_id'] = $userInfo->su_id;

        return $data;
    }

	/**
     * Function updateUser that pass parameter
     *
     * @param varchar $input the varchar to quote
	 *
	 * @return parameter.
     */
    public static function updateUser($input)
	{
        $user = Console_User::find($input['su_id']);

        $profileid = $user->profile->sup_id;
        $status = $user->su_status;

        if (isset($input['gantung']) && $input['gantung'] == 1) {
            $user->su_status = 2;
        } else if ($user->su_status != 'Pengesahan') {
            $user->su_status = 1;
        }

        if ($status == 'Baru') {
            $user->su_password = Hash::make($input['su_password']);
            $user->su_username = $input['sup_emel'];
            $user->su_validationkey = $input['key'];
            $user->su_status = 3;
        } else {
            unset($input['su_password']);
            unset($input['key']);
        }
        
        $user->sur_id = $input['sur_id'];
        $user->save();

        $profile = Console_Profile::find($profileid);
        if ($status == 'Baru') {
            $profile->wp_cipta_oleh = Auth::user()->su_id;
            $profile->wp_tarikh_emel_katalaluan = date('Y-m-d');
        }
        $profile->sup_nama = $input['sup_nama'];
        $profile->sup_id_pengguna = $input['sup_id_pengguna'];
        $profile->sup_no_ic = $input['sup_no_ic'];
        $profile->sup_emel = $input['sup_emel'];
        $profile->sup_tel = $input['sup_tel'];
        $profile->sup_no_pekerja = $input['sup_no_pekerja'];
        $profile->wjkp_no_auto = $input['wjkp_no_auto'];
        $profile->wpj_no_auto = $input['wpj_no_auto'];
        $profile->wpb_no_auto = $input['wpb_no_auto'];
        $profile->wpu_no_auto = $input['wpu_no_auto'];
        $profile->sup_is_supervisor = isset($input['sup_is_supervisor'])?1:0;
        $profile->sup_penyelia_satu = $input['sup_penyelia_satu'];
        $profile->sup_penyelia_dua = isset($input['sup_penyelia_dua'])?$input['sup_penyelia_dua']:0;
        $profile->wp_tarikh_mula = date('Y-m-d', strtotime($input['wp_tarikh_mula']));
        $profile->wp_tarikh_tamat = ($input['wp_tarikh_tamat'] != '')?date('Y-m-d', strtotime($input['wp_tarikh_tamat'])):'';
        $profile->wp_kemaskini_oleh = Auth::user()->su_id;
        $profile->sup_tidak_kelihatan = isset($input['sup_tidak_kelihatan'])?1:0;
        $profile->save();

        $profile = Console_User::find($input['su_id']);

        Log::write(
			'User',
			'Update User '.(($status == 'Baru')?
			$input['sup_no_ic']:$user->profile->sup_no_ic).' 
			By <code>'.Auth::user()->su_username.'</code>'
		);
		Trail::log(
			'Pengguna',
			Auth::user()->su_id,
			'Kemaskini Pengguna '.(($status == 'Baru')?
			$input['sup_no_ic']:$user->profile->sup_no_ic ).' 
			Oleh <code>'.Auth::user()->su_username.'</code>'
		);
		
        return $status;
    }

}

?>